﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SqlShareAPI
{
    /// <summary>
    /// A factory to create and build objects that require a specific database connection
    /// </summary>
    public class SSAPIFactory
    {
        SSSqlConnection _conn;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="metaConnectionString"></param>
        /// <param name="adminContentConnectionString"></param>
        public SSAPIFactory(string metaConnectionString, string adminContentConnectionString)
        {
            _conn = new SSSqlConnection(metaConnectionString, adminContentConnectionString);            
        }

        public UserSession CreateUserSessionViaPassword(string username, string password)
        {
            SSAuthentication auth = new SSAuthentication(username, _conn);
            if (!auth.AuthenticatePassword(password))
            {
                throw new Exception("Invalid user credentials");
            }
            return auth.GetUserSession();
        }

        public UserSession CreateUserSessionViaToken(string username, string token)
        {
            SSAuthentication auth = new SSAuthentication(username, _conn);
            if (!auth.AuthenticateToken(token))
            {
                throw new Exception("Invalid token for user");
            }
            return auth.GetUserSession();
        }    

        public SSAuthentication CreateAuthentication(string username)
        {
            return new SSAuthentication(username, _conn);
        }

        /// <summary>
        /// because we establish a SQL connection with each factory, the factory maintains the connection, when we are completely
        /// done with our session, we want to make sure to close the connection.
        /// </summary>
        public void Close()
        {
            _conn.CloseAll();
        }
    }
}
